import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

import '../../../controllers/auth_controller.dart';
import '../../../services/storage/file_storage_service.dart';

/// 编辑个人资料控制器
class EditProfileController extends GetxController {
  // 注入依赖
  final AuthController _authController = Get.find<AuthController>();
  // final FileStorageService _fileStorageService = Get.find<FileStorageService>(); // 假设有文件存储服务
  
  // 表单 Key
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  // 输入控制器
  late TextEditingController nameController;
  late TextEditingController emailController; // 邮箱通常不可编辑，但可以显示
  late TextEditingController bioController; // 个人简介

  // 头像相关
  final RxString _avatarUrl = ''.obs;
  String get avatarUrl => _avatarUrl.value;
  final Rx<File?> _selectedAvatarFile = Rx<File?>(null);
  File? get selectedAvatarFile => _selectedAvatarFile.value;

  // 加载状态
  final RxBool _isLoading = false.obs;
  bool get isLoading => _isLoading.value;

  @override
  void onInit() {
    super.onInit();
    // 初始化表单数据
    _loadInitialData();
  }

  @override
  void onClose() {
    nameController.dispose();
    emailController.dispose();
    bioController.dispose();
    super.onClose();
  }

  /// 加载初始数据
  void _loadInitialData() {
    _avatarUrl.value = _authController.userAvatarUrl;
    nameController = TextEditingController(text: _authController.userName);
    emailController = TextEditingController(text: _authController.userEmail);
    bioController = TextEditingController(text: _authController.userBio); // 假设AuthController有用户简介
  }

  /// 选择头像
  Future<void> pickAvatar() async {
    final ImagePicker picker = ImagePicker();
    try {
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);
      if (image != null) {
        _selectedAvatarFile.value = File(image.path);
        // 更新UI显示选中的头像
        _avatarUrl.value = ''; // 清空网络URL，优先显示本地文件
      }
    } catch (e) {
      Get.snackbar('错误', '选择图片失败: $e');
    }
  }

  /// 保存更改
  Future<void> saveProfile() async {
    if (formKey.currentState!.validate()) {
      _isLoading.value = true;
      try {
        String? uploadedAvatarUrl;
        // 1. 上传头像（如果选择了新头像）
        if (_selectedAvatarFile.value != null) {
          // uploadedAvatarUrl = await _fileStorageService.uploadFile(
          //   _selectedAvatarFile.value!,
          //   path: 'avatars/${_authController.userId}',
          // );
          // 模拟上传成功
          await Future.delayed(const Duration(seconds: 1));
          uploadedAvatarUrl = 'https://example.com/new_avatar.jpg'; 
        }

        // 2. 更新用户信息
        await _authController.updateUserProfile(
          name: nameController.text,
          bio: bioController.text,
          avatarUrl: uploadedAvatarUrl, // 传递新的头像URL或null
        );

        Get.back(); // 返回个人资料页
        Get.snackbar('成功', '个人资料已更新');

      } catch (e) {
        Get.snackbar('保存失败', e.toString(), backgroundColor: Colors.red, colorText: Colors.white);
      } finally {
        _isLoading.value = false;
      }
    }
  }
  
  // 验证规则
  String? validateName(String? value) {
    if (value == null || value.isEmpty) {
      return '姓名不能为空';
    }
    return null;
  }
} 